package com.devshephard.nio.chat.server;

import com.alibaba.fastjson.JSON;
import com.devshephard.nio.chat.session.LoginUserFactory;
import com.devshephard.nio.chat.session.SessionFactory;
import com.devshephard.nio.chat.user.User;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ChatServer {
    public static void main(String[] args) {

        SessionFactory sessionFactory = new SessionFactory();

        LoginUserFactory loginUser = new LoginUserFactory();


        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new StringDecoder());
                        channel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                System.out.println(msg);

                                //如果登录成功,则不需要校验登录
                                String loginUserName = sessionFactory.getOnliceChannelUserMap().get(channel);
                                if(!Objects.isNull(loginUserName)){

                                    String msgStr = (String)msg;
                                    List<String> msgList = Stream.of(msgStr.split(",")).collect(Collectors.toList());;
                                    //找到目标方的信道,进行传输
                                    Channel targetChannel = (Channel) sessionFactory.getOnliceUserMap().get(msgList.get(0));

                                    if(Objects.isNull(targetChannel)){
                                        ctx.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes("目标用户未登录...".getBytes()));
                                    }else{
                                        targetChannel.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes(msgList.get(1).getBytes()));
                                    }

                                }else{

                                    User user = JSON.parseObject((String) msg,User.class);
                                    String hasUserPwd = loginUser.getLoginUserMap().get(user.getName()); //表示已经注册的用户

                                    if(!Objects.isNull(hasUserPwd) && hasUserPwd.equals(user.getPassword())) //用户存在且密码正确
                                    {
                                        //将频道加入到sessionfactory
                                        sessionFactory.getOnliceUserMap().put(user.getName(),channel);
                                        sessionFactory.getOnliceChannelUserMap().put(channel,user.getName());
                                        //返回登录成功信息
                                        System.out.println(user.getName() + " 已登录" );
                                        ctx.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes("登录成功".getBytes()));
                                    }else {
                                        //返回登录失败信息
                                        ctx.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes("登录失败！".getBytes()));
                                    }
                                }
                            }
                        });
                    }
                })
                .bind(8100);
    }
}
